package com.bbva.general.core.session;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bbva.general.generics.Constantes;

public class SessionFilter implements Filter {

	private  ArrayList<String> urlList;//TablaGeneral
	private static String[] URL_EXCLUDE={"services/TablaGeneral/wsdl/TablaGeneral.wsdl",
										"/services/TablaGeneral/wsdl",
										"/services/TablaGeneral"};
	 
    public void destroy() {
    }
 
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
 
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String url = request.getServletPath();
        
        for(String url_:URL_EXCLUDE){
        	if (url_.equals(url)) {
        		chain.doFilter(request, response);
        		return;
        	}
        }
        boolean allowedRequest = false;
 
        if(urlList.contains(url)) {
            allowedRequest = true;
        }
 
        if (!allowedRequest) {
            HttpSession session = request.getSession(false);
            if (null == session) {
                response.sendRedirect(request.getContextPath()+"/web/seguridad/errorsesion.jsp");
                return;
            }else if(session!= null && session.getAttribute((Constantes.SESSION_USER))== null){
            	response.sendRedirect(request.getContextPath()+"/web/seguridad/error.jsp");
                return;
            }
        }
 
        chain.doFilter(req, res);
    }
 
    public void init(FilterConfig config) throws ServletException {
        String urls = config.getInitParameter("avoid-urls");
        StringTokenizer token = new StringTokenizer(urls, ",");
 
        urlList = new ArrayList<String>();
        urlList.add("");
        urlList.add("/web/seguridad/errorsesion.jsp");
        urlList.add("/web/seguridad/error.jsp");
        urlList.add("/AccesoServlet.do");        
        while (token.hasMoreTokens()) {
            urlList.add(token.nextToken()); 
        }
    }

}

